﻿using MediatR;
using SCM.API.Write.Application.Command.Purchase;
using SCM.Domain;
using SCM.ErrorCode;
using SCM.Infrastructure.Implement;

namespace SCM.API.Write.Application.Handler.Purchase
{
    public class UpdateRecordedHandler : IRequestHandler<UpdateRecordedCommand, APIResult<int>>
    {
        DatabaseContext db;

        public UpdateRecordedHandler(DatabaseContext db)
        {

            this.db = db;
        }
        public Task<APIResult<int>> Handle(UpdateRecordedCommand request, CancellationToken cancellationToken)
        {
            APIResult<int> result = new APIResult<int>();
            var res = db.SqlSugar.Queryable<PurchaseManagementModel>().Where(x => x.Id == request.Id).First();
            if (res == null)
            {
                result.Code = APIEnum.Fail;
                result.Msg = "不存在";
                return Task.FromResult(result);
            }
            if (res.Recorded == true)
            {
                result.Code = APIEnum.Fail;
                result.Msg = "产品已入账";
                return Task.FromResult(result);
            }
            
            res.Recorded = request.Recorded;
            
            int r = db.SqlSugar.Updateable(res).ExecuteCommand();
            if (r > 0)
            {
                result.Msg = "入账成功";
                result.Data = r;
                result.Code = APIEnum.Success;
            }
            else
            {
                result.Msg = "入账失败";
                result.Data = r;
                result.Code = APIEnum.Fail;
            }
            return Task.FromResult(result);
        }
    }
}
